package com.myc.train.common.controller;


import cn.hutool.core.util.StrUtil;
import com.myc.train.common.exception.BusinessException;
import com.myc.train.common.resp.CommonResp;
import io.seata.core.context.RootContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
public class ControllerExceptionHandler {

    private static final Logger LOG= LoggerFactory.getLogger(ControllerExceptionHandler.class);

    /**
     * 系统异常
     * */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonResp exceptionHandler(Exception e) throws Exception {
//         LOG.info("seata全局事务ID: {}", RootContext.getXID());
//         // 如果是在一次全局事务里出异常了，就不要包装返回值，将异常抛给调用方，让调用方回滚事务
//         if (StrUtil.isNotBlank(RootContext.getXID())) {
//             throw e;
//         }
        CommonResp resp = new CommonResp();
        LOG.error("系统异常：",e);
        resp.setSuccess(false);
        resp.setMessage("系统出现异常，未知异常");
        return resp;

    }
    /**
     * 业务异常
     * */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public CommonResp exceptionHandler(BusinessException e){
        CommonResp resp = new CommonResp();
        LOG.error("业务异常：{}",e.getE().getDesc());
        resp.setSuccess(false);
        resp.setMessage(e.getE().getDesc());
        return resp;

    }
    /**
     * 校验异常
     * */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public CommonResp exceptionHandler(BindException e){
        CommonResp resp = new CommonResp();
        String err = "";
        BindingResult bindingResult=e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        for (ObjectError allError : allErrors) {
            err = err + allError.getDefaultMessage();
            LOG.error("业务异常：{}",err);
        }
        resp.setSuccess(false);
        resp.setMessage(err);
        return resp;

    }
}
